/**
 * java多线程模式
 * @author andy.rong
 */
package com.myjavalab.thread;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Random;

public class BalkingPattern {

	public static void main(String[] args) {
		Data data = new Data("data.txt", "(empty)");
		new ChangerThread("changer", data).start();
		new SaverThread("saver", data).start();
	}
}

class Data {
	private final String fileName;
	private String content;
	private boolean changed;
	
	public Data(String fileName, String content) {
		this.fileName = fileName;
		this.content = content;
		this.changed = true;
	}
	
	public synchronized void change(String newContent) {
		content = newContent;
		changed = true;
	}
	
	public synchronized void save() throws IOException {
		if(!changed) {
			return;
		}
		doSave();
		changed = false;
	}
	
	private void doSave() throws IOException {
		System.out.println(Thread.currentThread().getName() + " call doSave, content = " + content);
		Writer writer = new FileWriter(fileName);
		writer.write(content);
		writer.close();
	}
}

class SaverThread extends Thread {
	private Data data;
	public SaverThread(String name, Data data) {
		super(name);
		this.data = data;
	}
	
	
	public void run() {
		try {
			while(true) {
				data.save();
				Thread.sleep(1000);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class ChangerThread extends Thread {
	private Data data;
	private Random random = new Random();
	public ChangerThread(String name, Data data) {
		super(name);
		this.data = data;
	}
	
	public void run() {
		try {
			for(int i = 0; true; i++) {
				data.change("No." + i);
				Thread.sleep(random.nextInt(1000));
				data.save();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}